package com.example.mediaplayer.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.mediaplayer.R;
import com.example.mediaplayer.base.BaseApp;
import com.example.mediaplayer.domain.FileInfo;
import com.example.mediaplayer.service.MyService;
import com.example.mediaplayer.ui.adapter.IshowShareView;
import com.example.mediaplayer.ui.adapter.MyAdapter;
import com.example.mediaplayer.utils.ViewUtil;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.db.sqlite.Selector;
import com.lidroid.xutils.exception.DbException;

public class MainActivity extends Activity implements IshowShareView {

	private static final String ACTION_PLAY = "com.share.ylh.mediaplayer.PLAY";
	private static final int DONE = 1;
	private int STATE = 0;// 1:play,2:psuse,3:stop;//7：上一首 8：下一首
	// 文件id
	private static int id = 1;
	private static int ListViewpostion;
	private TextView cancel;
	private LinearLayout share, buttonmenu, playbar, toMyActivity;
	private List<HashMap<String, String>> filelists;
	private ListView mListView;
	private MyAdapter adapter;
	private ProgressDialog mProgressDialog;
	private DbUtils db;
	private ImageView playerprebtn, playerplaybtn, playerpausebtn,
			playernextbtn;

	private Handler mhandler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);

			if (msg.what == DONE) {

				// 保存数据库
				FileInfo fileInfo;
				for (int i = 0; i < filelists.size(); i++) {

					try {

						FileInfo f = db.findFirst(Selector.from(FileInfo.class)
								.where("id", "=", i));
						if (null == f) {
							fileInfo = new FileInfo();
							fileInfo.setId(i);
							fileInfo.setFilePath(filelists.get(i).get(
									"filePath"));
							db.save(fileInfo);
						}
					} catch (DbException e) {
						e.printStackTrace();
					}
				}
				adaptNodify();
			}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initSharep();
		initView();
		playbarisshow();
		initEvent();
		initService();

		try {

			String count = ViewUtil.getShardPStringByKey("count");
			/*
			 * 如果数据库没数据，初始化
			 */
			if ("".equals(count)) {
				mProgressDialog.show();
				searchMusic();
			} else {
				/*
				 * 从数据库取数据
				 */
				filelists = new ArrayList<HashMap<String, String>>();
				List<FileInfo> list = db.findAll(FileInfo.class);// 通过类型查找
				HashMap<String, String> map;
				for (int i = 0; i < list.size(); i++) {
					map = new HashMap<String, String>();
					map.put("fileName",
							list.get(i)
									.getFilePath()
									.substring(
											list.get(i).getFilePath()
													.lastIndexOf("/") + 1,
											list.get(i).getFilePath()
													.lastIndexOf(".") - 1));

					map.put("id", list.get(i).getId() + "");

					map.put("fileType",
							list.get(i)
									.getFilePath()
									.substring(
											list.get(i).getFilePath()
													.lastIndexOf(".") + 1));

					filelists.add(map);

				}
				adaptNodify();
			}

		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 扫描文件
	 */
	private void searchMusic() {
		mProgressDialog.show();
		new Thread(new Runnable() {
			@Override
			public void run() {

				filelists = ViewUtil.getMusicListOnSys(
						ViewUtil.getExternalStoragePath(), "mp3");

				// 保存歌曲数量
				ViewUtil.setShardPString("count", filelists.size() + "");
				Message message = Message.obtain();
				message.what = DONE;
				mhandler.sendMessage(message);
			}
		}).start();
	}

	private void initView() {

		// 创建数据库
		// fileService = new FileService(this);
		db = DbUtils.create(this);

		mListView = (ListView) findViewById(R.id.playerlists);
		filelists = new ArrayList<HashMap<String, String>>();

		playerprebtn = (ImageView) findViewById(R.id.playerprebtn);
		playerplaybtn = (ImageView) findViewById(R.id.playerplaybtn);
		playerpausebtn = (ImageView) findViewById(R.id.playerpausebtn);
		playernextbtn = (ImageView) findViewById(R.id.playernextbtn);

		share = (LinearLayout) findViewById(R.id.share);
		cancel = (TextView) findViewById(R.id.cancel);
		buttonmenu=(LinearLayout)findViewById(R.id.buttonmenu);

		// 实例化 进度条
		mProgressDialog = new ProgressDialog(this);
		mProgressDialog.setTitle("提示");
		mProgressDialog.setMessage("正在搜索mp3文件，请稍后...");
		mProgressDialog.setCancelable(false);
	}

	private void initEvent() {

		mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				ListView lv = (ListView) parent;
				// Cursor cursor = (Cursor)lv.getItemAtPosition(position);
				HashMap<String, String> music = (HashMap<String, String>) lv
						.getItemAtPosition(position);
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, PlayActivity.class);
				intent.putExtra("playid", music.get("id"));// 文件id（1,2,3） 不是路径
				ViewUtil.setShardPString("id", music.get("id"));
				ViewUtil.setShardPString("STATE", "9");
				Toast.makeText(getApplicationContext(), music.get("id"),
						Toast.LENGTH_LONG).show();
				startActivity(intent);
			}
		});

		playerprebtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				if ((id - 1) >= 0) {
					id = id - 1;
				} else {
					id = 0;
					Toast.makeText(getApplicationContext(), "已经是第一首歌",
							Toast.LENGTH_SHORT).show();
				}
				Log.e("playerprebtn====>id", "" + id);
				ViewUtil.setShardPString("id", id + "");
				updateState(1);
				playingView();

			}
		});

		playernextbtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				if ((id + 1) <= filelists.size()) {
					id = (id + 1);
				} else {
					id = filelists.size();
					Toast.makeText(getApplicationContext(), "已经是最后一首歌",
							Toast.LENGTH_SHORT).show();
				}
				Log.e("playernextbtn====>id", "" + id);
				ViewUtil.setShardPString("id", id + "");
				updateState(1);
				playingView();
			}
		});
		playerplaybtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {

				updateState(1);
				playingView();
			}
		});
		playerpausebtn.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				updateState(2);
				pausingView();
			}
		});

		share.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				String title = "音乐同享";
				String content = "我正在听"
						+ filelists.get(ListViewpostion).get("fileName");
				String url = "";
				// 分享到
				// ViewUtil.showShareDialog(PlayActivity.this, title,content,
				// url);
				ViewUtil.showShareMore(MainActivity.this, title, content, url);
			}
		});

		cancel.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				buttonmenu.setVisibility(View.GONE);
			}
		});
	}

	private void updateState(int state) {
		// STATE = state;
		ViewUtil.setShardPString("STATE", state + "");
		sendOperateBroadCast();
	}

	private void sendOperateBroadCast() {

		// 发送广播to PlayActivity，

		id = Integer.parseInt(ViewUtil.getShardPStringByKey("id"));
		ViewUtil.setShardPString("id", id + "");// 上一首下一首后刷新id
		Intent intent = new Intent("com.share.ylh.mediaplayer.topreview");
		BaseApp.AppContext.sendBroadcast(intent);
	}

	private void adaptNodify() {

		adapter = new MyAdapter(getApplicationContext(), filelists,
				R.layout.player);
		mListView.setAdapter(adapter);

		adapter.setIshowview(this);
		mProgressDialog.dismiss();
	}

	/**
	 * 播放时界面变化
	 */
	private void playingView() {
		playerplaybtn.setVisibility(View.GONE);
		playerpausebtn.setVisibility(View.VISIBLE);
	}

	/**
	 * 暂停时界面变化
	 */
	private void pausingView() {
		playerpausebtn.setVisibility(View.GONE);
		playerplaybtn.setVisibility(View.VISIBLE);
	}

	/**
	 * 初始化service
	 */
	private void initService() {
		Intent intent = new Intent();
		intent.setClass(MainActivity.this, MyService.class);
		intent.setAction(ACTION_PLAY);
		startService(intent);
	}

	/**
	 * 首次启动为空 进行初始化
	 */
	private void initSharep() {
		if ("".equals(ViewUtil.getShardPStringByKey("id"))) {
			ViewUtil.setShardPString("id", "1");
		}

		if ("".equals(ViewUtil.getShardPStringByKey("STATE"))) {
			ViewUtil.setShardPString("STATE", "0");
		}
		if ("".equals(ViewUtil.getShardPStringByKey("playstate"))) {
			ViewUtil.setShardPString("playstate", "4");
		}
	}

	private void playbarisshow() {

		// 初始化状态和文件id
		STATE = Integer.parseInt(ViewUtil.getShardPStringByKey("STATE"));
		id = Integer.parseInt(ViewUtil.getShardPStringByKey("id"));

		if ("1".equals(STATE + "")) {
			playingView();
		} else if ("2".equals(STATE + "")) {
			pausingView();
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.reflash:
			mProgressDialog.show();
			searchMusic();
			break;

		}
		return super.onOptionsItemSelected(item);
	}

	@Override
	public void showView(int pos) {
		// TODO Auto-generated method stub
		ListViewpostion = pos;
		buttonmenu.setVisibility(View.VISIBLE);
	}

}
